package com.huyu.substat.modules.substat.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.easy.excel.ExcelExport;
import org.easy.excel.ExcelExportResult;
import org.easy.excel.ExcelHeader;
import org.easy.excel.vo.ExcelDefinition;
import org.easy.excel.vo.FieldValue;
import org.springframework.web.context.WebApplicationContext;

import com.thinkgem.jeesite.common.utils.Util;
import com.thinkgem.jeesite.common.utils.UtilDate;

public class FileDownloadService extends BaseSubjectService {
	private static final Logger logger = Logger.getLogger(FileImportService.class);

	public Map<String, Object> genExcelTemplateFile(String className, WebApplicationContext appContext,
			String realPath) {
		this.appContext = appContext;
		Map<String, Object> rm = new HashMap<String, Object>();
		try {
			Map<String, String> table = getTableMap(className);
			String savePath = realPath;
			savePath = savePath + "/downloads";
			String tableComments = Util.o2s(table.get("comments"));
			if (!new File(savePath).exists()) {
				new File(savePath).mkdirs();
			}
			String fileName = tableComments + "-" + UtilDate.getCurrentTimestamp().getTime() / 1000 + ".xlsx";
			rm.put("fileName", fileName);
			savePath = savePath + File.separator + fileName;
			rm.put("path", savePath);
			logger.info("download fileName: " + fileName+", savePath: "+savePath);

			ExcelExport export = new ExcelExport(null);
			ExcelDefinition excelDefinition = new ExcelDefinition();
			List<FieldValue> fieldValues = getFieldValues(className, table);
			excelDefinition.setFieldValues(fieldValues);

			List<?> beans = null;
			ExcelHeader header = new ExcelHeader() {
				@Override
				public void buildHeader(Sheet sheet, ExcelDefinition excelDefinition, List<?> beans) {
					// 允许没有头部row
				}
			};

			ExcelExportResult exportResult = export.doCreateExcel(excelDefinition, beans, header);
			// exportResult.append(getStudents()); //这里附加行数据

			Workbook workbook = exportResult.build();
			OutputStream ops = new FileOutputStream(savePath);
			workbook.write(ops);
			ops.close();
			workbook.close();
		} catch (Exception e) {
			logger.error("createExcel failed", e);
		}

		return rm;
	}
}
